﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WinSat
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            textBox1.Focus();
        }

        public void CariListe(string filtre)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                using (Query q = new Query())
                {
                    q.Add("@kod", SqlDbType.NVarChar, filtre + '%', 50);
                    q.Add("SELECT     code AS [Müşteri Kodu], name AS [Müşteri Ünvanı],logged_in as giris_yapildi,adress,telnumber,faxnumber,order_series,seller_person,district FROM         CUSTOMERS WITH (NOLOCK) WHERE  (code not like '320%') and  (name LIKE @kod or code like @kod)");
                    dataGrid1.VeriKaynagi = q.Fill();
                    dataGrid1.Columns[0].Width = 80;
                    dataGrid1.Columns[1].Width = 200;
                    dataGrid1.Columns[2].Width = 0;
                    dataGrid1.Columns[3].Width = 0;
                    dataGrid1.Columns[4].Width = 0;
                    dataGrid1.Columns[5].Width = 0;
                    dataGrid1.Columns[6].Width = 0;
                    dataGrid1.Columns[7].Width = 0;
                    dataGrid1.Columns[8].Width = 0;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    CariListe(textBox1.Text);
                    if (dataGrid1.RowCount == 1)
                    {
                        Cari cari = new Cari();
                        cari.Kodu = dataGrid1[0, 0].ToString();
                        cari.Adi = dataGrid1[0, 1].ToString();
                        cari.Adres = dataGrid1[0, 3].ToString() + dataGrid1[0, 4].ToString() + dataGrid1[0, 5].ToString();
                        cari.EvrakSeri = CariSeri();
                        cari.TemsilciBolge = dataGrid1[0, 7].ToString() + "/" + dataGrid1[0, 8].ToString();
                        bool giris = Cevir.Parse<bool>(dataGrid1[0, 2]);
                        SipariseBasla(cari, giris);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CariListe(textBox1.Text);
        }

        bool klavyeAcik = false;
        private void button3_Click(object sender, EventArgs e)
        {
            if (klavyeAcik)
            {
                klavyeAcik = false;
                Sip.Hide();
            }
            else
            {
                klavyeAcik = true;
                Sip.Show();
            }
            textBox1.Focus();
        }

        private void SipariseBasla(Cari cari, bool girisyapildi)
        {
            try
            {
                //if (girisyapildi)
                //{

                //}
                //else
                //    MessageBox.Show("Cari Giriş’i Yapılmamış,Lutfen Kayıt bankosundan Giriş Yaptırınız.");

                frmSiparis sip = new frmSiparis();
                if (Program.Session[Settings.BaglantiTipi].ToString() == "local")
                {
                    sip.EvrakSeri = Program.Session[Settings.EvrakSeri].ToString();
                }
                else
                {
                    sip.EvrakSeri = cari.EvrakSeri;
                }

                sip.Cari = cari;
                sip.Show();
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGrid1.CurrentRowIndex > -1)
                {
                    Cari cari = new Cari();
                    cari.Kodu = dataGrid1[0, 0].ToString();
                    cari.Adi = dataGrid1[0, 1].ToString();
                    cari.Adres = dataGrid1[0, 3].ToString() + dataGrid1[0, 4].ToString() + dataGrid1[0, 5].ToString();
                    cari.EvrakSeri = CariSeri();
                    cari.TemsilciBolge = dataGrid1[0, 7].ToString() + "/" + dataGrid1[0, 8].ToString();
                    bool giris = Cevir.Parse<bool>(dataGrid1[dataGrid1.CurrentRowIndex, 2]);
                    SipariseBasla(cari, giris);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        public string CariSeri()
        {
            string seri = "";
            if (Program.Session[Settings.BaglantiTipi].ToString() == "local")
            {
                seri = Program.Session[Settings.EvrakSeri].ToString();
            }
            else
            {
                using (Query q = new Query())
                {
                    q.Add(string.Format("exec sp_executesql N'SELECT     order_series  FROM         CUSTOMERS  WHERE     (code = ''{0}'')'", Program.Session[Settings.Tedarikci]));
                    seri = q.ExecScaler<string>();
                    q.Clear();
                }
            }
            return seri;
        }

        private void dataGrid1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (dataGrid1.CurrentRowIndex > -1)
                {
                    Cari cari = new Cari();
                    cari.Kodu = dataGrid1[dataGrid1.CurrentRowIndex, 0].ToString();
                    cari.Adi = dataGrid1[dataGrid1.CurrentRowIndex, 1].ToString();
                    cari.Adres = dataGrid1[dataGrid1.CurrentRowIndex, 3].ToString() + dataGrid1[dataGrid1.CurrentRowIndex, 4].ToString() + dataGrid1[dataGrid1.CurrentRowIndex, 5].ToString();
                    cari.EvrakSeri = CariSeri();
                    cari.TemsilciBolge = dataGrid1[dataGrid1.CurrentRowIndex, 7].ToString() + "/" + dataGrid1[dataGrid1.CurrentRowIndex, 8].ToString();
                    bool giris = Cevir.Parse<bool>(dataGrid1[dataGrid1.CurrentRowIndex, 2]);
                    SipariseBasla(cari, giris);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandling.Hand(ex);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Program.Session.CloseSession();
            this.Close();
        }

        private void btnDegistir_Click(object sender, EventArgs e)
        {
            frmEvraklar liste = new frmEvraklar();
            liste.Show();
        }

        private void frmMain_Activated(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox1.Focus();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            using (Query q = new Query())
            {
                q.Add("SELECT     SUM(total)  FROM         ORDER_DETAILS");
                decimal toplam = q.ExecScaler<decimal>();
                MessageBox.Show(toplam.ToString("n2"));
            }
        }

        private static void NetworkTest()
        {
            NetTools t = new NetTools();
            if (t.IsConnected)
            {
                MessageBox.Show("Terminal Network Bağlı");
            }
            else
            {
                MessageBox.Show("Terminal Network Bağlı Değil !");
            }

            if (Program.Session[Settings.BaglantiTipi].ToString() != "servis")
            {
                if (t.IsConnected2)
                {
                    MessageBox.Show("Sql Sunucuya Bağlandı");
                }
                else
                {
                    MessageBox.Show("Sql Sunucuya Bağlanamadı !");
                }
            }
        }

        bool islemDevamediyor = false;
        private void btnAktar_Click(object sender, EventArgs e)
        {
            try
            {
                if (!islemDevamediyor)
                {
                    backgroundWorker1.RunWorkerAsync();
                }
                else
                {
                    MessageBox.Show("gönderiliyor... lütfen bekleyin !");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bazı evraklarınız aktarılmamış olabilir lütfen evrak listesinden kontrol edin ve tekrar göndermeyi deneyin !" + ex.Message);
            }
        }


        private void EvrakAktar()
        {
            using (Query q = new Query())
            {
                q.Add("select order_series,order_no from ORDER_DETAILS where terminal = 0 group by order_series,order_no");
                DataTable dt = q.Fill();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    q.Clear();
                    q.Add(string.Format("select  rec_id, order_series, order_no, order_date, customer_code, product_code, barcode, amount, price, total, vat, vatsum, currency, supplier, printed, discount1, discount2,discount3, comment, terminal, authorized_person from ORDER_DETAILS WHERE order_series='{0}' and order_no={1}", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString()));
                    EvrakKayit(q.Fill());

                    q.Clear();
                    q.Add(string.Format("UPDATE ORDER_DETAILS SET printed=1,terminal=1 WHERE (order_series = '{0}') AND (order_no = {1}) ", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString()));
                    q.Exec();
                }
            }
        }

        private void EvrakKayit(DataTable dt)
        {
            try
            {
                using (Query q = new Query(ProgramTipleri.DirectSql))
                {
                    string insertSql = "insert into ORDER_DETAILS (order_series, order_no, order_date, customer_code, product_code, barcode, amount, price, total, vat, vatsum, currency,supplier,printed,discount1,discount2,discount3,comment,terminal) values (@order_series, @order_no, @order_date, @customer_code, @product_code, @barcode, @amount, @price, @total, @vat, @vatsum, @currency,@supplier,1,@isk1,@isk2,@isk3,@comment,1)";
                    string deleteSql = " delete from ORDER_DETAILS where order_series=@order_series and order_no=@order_no";

                    q.Add("@order_series", SqlDbType.NVarChar, dt.Rows[0]["order_series"].ToString(), 5);
                    q.Add("@order_no", SqlDbType.Int, dt.Rows[0]["order_no"]);
                    q.Add(deleteSql);
                    q.Exec();
                    q.Clear();

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["product_code"] != DBNull.Value && dt.Rows[i]["product_code"] != null)
                        {
                            q.Add("@order_series", SqlDbType.NVarChar, dt.Rows[i]["order_series"].ToString(), 5); //1
                            q.Add("@order_no", SqlDbType.Int, Convert.ToInt32(dt.Rows[i]["order_no"])); //2
                            q.Add("@order_date", SqlDbType.DateTime, Convert.ToDateTime(dt.Rows[i]["order_date"]));  //3
                            q.Add("@customer_code", SqlDbType.NVarChar, dt.Rows[i]["customer_code"].ToString(), 25); //4
                            q.Add("@product_code", SqlDbType.NVarChar, dt.Rows[i]["product_code"].ToString(), 25); //5
                            q.Add("@barcode", SqlDbType.NVarChar, dt.Rows[i]["barcode"].ToString(), 25); //6
                            q.Add("@amount", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["amount"])); //7
                            q.Add("@price", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["price"])); //8
                            q.Add("@total", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["total"])); //9
                            q.Add("@vat", SqlDbType.Int, Convert.ToInt32(dt.Rows[i]["vat"])); //10
                            q.Add("@vatsum", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["vatsum"])); //11
                            q.Add("@currency", SqlDbType.Int, Convert.ToInt32(dt.Rows[i]["currency"])); //12
                            q.Add("@supplier", SqlDbType.NVarChar, Program.Session[Settings.Tedarikci].ToString()); //13
                            q.Add("@isk1", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["discount1"])); //14
                            q.Add("@isk2", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["discount2"])); //15
                            q.Add("@isk3", SqlDbType.Float, Convert.ToDecimal(dt.Rows[i]["discount3"])); //16
                            q.Add("@comment", SqlDbType.NVarChar, dt.Rows[i]["comment"], 500); //17
                            q.Add(insertSql);
                            q.Exec();
                            q.Clear();
                        }
                    }

                    q.Clear();

                    q.Add(string.Format("UPDATE ORDER_DETAILS SET printed=0,terminal=1 WHERE (order_series = '{0}') AND (order_no = {1}) ", dt.Rows[0]["order_series"].ToString(), dt.Rows[0]["order_no"].ToString()));
                    q.Exec();

                    q.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            islemDevamediyor = true;
            EvrakAktar();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Evraklar Aktarıldı !");
            islemDevamediyor = false;
        }

    }
}